import {clone, getMeta} from "@src/util/util";
import Constant from "@src/util/constant";
import dictSql from "@src/sql/dictSql";

// 添加数据字典
const add = async (typeId: string, name: string) => {
  const isFlag = await dictSql.add(typeId, name);
  if (isFlag) {
    return clone(Constant.ADD_DEFAULT_SUCCESS);
  } else {
    if (isFlag === 0) {
      return clone(Constant.CATEGORY_ERROR);
    } else {
      return clone(Constant.ADD_ERROR);
    }
  }
};

//更新数据字典
const update = async (id: string, typeId: string, name: string) => {
  if (!(await dictSql.isCategoryId(id))) {
    return Constant.CATEGORY_ERROR;
  }
  const isFlag: boolean | number = await dictSql.update(id, typeId, name);
  if (isFlag) {
    return clone(Constant.DEFAULT_SUCCESS);
  } else {
    return clone(Constant.CATEGORY_ERROR);
  }
};

// 删除数据字典
const _delete = async (id: string) => {
  if (!(await dictSql.isCategoryId(id))) {
    return Constant.CATEGORY_ERROR;
  }
  await dictSql._delete(id);
  return clone(Constant.DEFAULT_SUCCESS);
};

// list
const list = async (page: number, size: number, filters: any) => {
  //从第几条开始查询
  const offset = (page - 1) * size;
  //查询多少条
  const {count, rows} = await dictSql.list(offset, size, filters);
  let resObj = clone(Constant.DEFAULT_SUCCESS);
  const meta = getMeta(count, page, size);
  return {
    ...resObj,
    meta,
    data: rows,
  };
};

// 查询分类下的字典
const category = async (type_id: string) => {
  const resObj = clone(Constant.DEFAULT_SUCCESS);
  const data: any = await dictSql.category(type_id);
  // 数据可能返回两种，true代表没有该分类，对象数组则是查询到的数据
  if (data === true) {
    return clone(Constant.CATEGORY_ERROR);
  }
  return {
    ...resObj,
    data,
  };
};

export default {
  add,
  update,
  _delete,
  list,
  category,
};